const db = require('../db')
const bcrypt = require('bcryptjs')
// const path = require("path");
const { formatTime, deleteFile } = require('../utils')

/**
 * 修改密码
 * @param {*} req
 * @param {*} res
 */
exports.updatePassword = (req, res) => {
  const { id } = req.auth
  const { new_password, old_password } = req.body
  // 执行SQL
  const selectSql = `select * from sys_user where id = ?`
  db.query(selectSql, id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length !== 1) return res.new_send('用户不存在')
    // 旧密码判断
    const compareResult = bcrypt.compareSync(old_password, results[0].password)
    if (!compareResult) return res.new_send('旧密码错误')
    // 新密码处理
    let newPassword = bcrypt.hashSync(new_password, 10)
    const updateSql = `update sys_user set password = ? where id = ?`
    db.query(updateSql, [newPassword, id], (err, results) => {
      if (err) return res.new_send(err)
      if (results.affectedRows !== 1) return res.new_send('更新密码失败')
      res.new_send('更新密码成功', 0)
    })
  })
}

/**
 * 修改头像
 * @param {*} req
 * @param {*} res
 * @returns
 */
exports.updateAvatar = (req, res) => {
  if (!req.file || req.file.fieldname !== 'avatar')
    return res.new_send('头像上传失败，请检查图片类型！')
  const { old_avatar } = req.body
  const avatarUrl = '/avatar/' + req.file.filename
  // 更新头像
  const updateSql = `update sys_user set avatar = ? where id = ?`
  db.query(updateSql, [avatarUrl, req.body.id], (err, results) => {
    if (err) return res.new_send(err)
    if (results.affectedRows !== 1) return res.new_send('更换头像失败')
    // 删除原来的头像
    old_avatar && deleteFile(old_avatar)
    // 成功返回结果
    // res.new_send("更换头像成功", 0);
    res.send({
      status: 0,
      message: '更换头像成功',
      avatar: avatarUrl
    })
  })
}

/**
 * 修改用户状态
 * @param {*} req
 * @param {*} res
 */
exports.updateUserStatus = (req, res) => {
  let { id, status } = req.body
  // 更新状态
  let updateSql = `update sys_user set status = ? where id = ?`
  db.query(updateSql, [status, id], (err, results) => {
    if (err) return res.new_send(err)
    if (results.affectedRows !== 1) return res.new_send('更新状态失败')
    res.new_send('更新状态成功', 0)
  })
}

/**
 * 删除用户
 * @param {*} req
 * @param {*} res
 */
exports.deleteUserById = (req, res) => {
  const { id } = req.params
  const deleteSql = `update sys_user set is_delete = 1 where id = ?`
  db.query(deleteSql, id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.affectedRows !== 1) return res.new_send('删除用户失败')
    res.new_send('删除用户成功', 0)
  })
}

/**
 * 获取用户列表
 * @param {*} req
 * @param {*} res
 */
exports.getUserList = (req, res) => {
  let { id, is_admin } = req.auth
  // 分页加载
  let page_num = req.query.page_num || 1 //当前的num
  let page_size = req.query.page_size || 10 //当前页的数量
  let start_num = (parseInt(page_num) - 1) * parseInt(page_size)

  if (is_admin) {
    // 管理员
    let selectSql = `select * from sys_user where is_delete = 0 `
    let { username } = req.body
    username && (selectSql += ` and username like '%${username}%' `)
    selectSql += ` limit ${start_num},${page_size}`
    db.query(selectSql, (err, results) => {
      if (err) return res.new_send(err)
      if (results.length > 0) {
        results.forEach((item) => {
          item.create_time = formatTime(item.create_time)
        })
        let users = results
        // 查询数据库总数
        let totalSql =
          'select count(*) as total from sys_user where is_delete = 0 '
        username && (totalSql += ` and username like '%${username}%' `)
        db.query(totalSql, (err, results) => {
          if (err) return res.new_send(err)
          let total = results[0]['total'] // 总数
          res.send({
            status: 0,
            message: '获取用户成功',
            total,
            data: users
          })
        })
      }
    })
  } else {
    // 非管理员
    const selectSql = `select * from sys_user where id = ?`
    db.query(selectSql, id, (err, results) => {
      if (err) return res.new_send(err)
      if (results.length > 0) {
        results.forEach((item) => {
          item.create_time = formatTime(item.create_time)
        })
      }
      res.send({
        status: 0,
        message: '获取用户成功',
        total: 1,
        data: results
      })
    })
  }
}

/**
 * 根据Id获取用户信息
 * @param {*} req
 * @param {*} res
 */
exports.getUserById = (req, res) => {
  const { id } = req.params

  const selectSql = `select * from sys_user where id = ?`
  db.query(selectSql, id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
    }
    res.send({
      status: 0,
      message: '获取用户成功',
      data: results
    })
  })
}

/**
 * 获取用户列表(已删除)
 * @param {*} req
 * @param {*} res
 */
exports.getUserListDel = (req, res) => {
  // 分页加载
  let page_num = req.query.page_num || 1 //当前的num
  let page_size = req.query.page_size || 10 //当前页的数量
  let start_num = (parseInt(page_num) - 1) * parseInt(page_size)
  let { username } = req.query

  let selectSql = `select * from sys_user where is_delete = 1` +
  (username ? ` and username like '%${username}%' `: '') +
  ` limit ${start_num},${page_size}`
  // username && (selectSql += ` and username like '%${username}%' `)
  // selectSql += ` limit ${start_num},${page_size}`
  db.query(selectSql, (err, results) => {
    if (err) return res.new_send(err)
    if (results.length > 0) {
      results.forEach((item) => {
        item.create_time = formatTime(item.create_time)
      })
      let users = results
      // 查询数据库总数
      let totalSql =
        'select count(*) as total from sys_user where is_delete = 1' +
        (username ? ` and username like '%${username}%' `: '')
      db.query(totalSql, (err, results) => {
        if (err) return res.new_send(err)
        let total = results[0]['total'] || 0 // 总数
        res.send({
          status: 0,
          message: '获取用户成功',
          page_num,
          page_size,
          total,
          data: users
        })
      })
    } else {
      res.send({
        status: 0,
        message: '获取用户成功',
        total: 0,
        data: []
      })
    }
  })
}

/**
 * 新增用户信息
 * @param {*} req
 * @param {*} res
 */
exports.addUser = (req, res) => {
  // 查询
  const selectSql = `select * from sys_user where username = ? or nick_name = ?`
  db.query(
    selectSql,
    [req.body.username, req.body.nick_name],
    (err, results) => {
      // 判断用户名和昵称是否存在
      if (results.length >= 2) return res.new_send('用户名和昵称已被占用')
      if (results.length === 1) {
        const { username, nick_name } = results[0]
        const { username: name, nick_name: nc_name } = req.body
        if (username === name && nick_name === nc_name) {
          return res.new_send('用户名和昵称已被占用')
        }
        if (username === name) {
          return res.new_send('用户名已被占用')
        }
        if (nick_name === nc_name) {
          return res.new_send('昵称已被占用')
        }
      }
      // 密码加密
      req.body.password = bcrypt.hashSync(req.body.password, 10)
      // 默认头像
      req.body.avatar = req.body.avatar || '/default/1.jpg'
      // 插入数据库
      const insertSql = `insert into sys_user set ?`
      db.query(insertSql, req.body, (err, results) => {
        if (err) return res.new_send(err)
        if (results.affectedRows !== 1) return res.new_send('新增用户失败')
        res.send({
          status: 0,
          message: '新增用户成功',
          data: { insertId: results.insertId }
        })
      })
    }
  )
}

/**
 * 修改标签
 * @param {*} req
 * @param {*} res
 */
exports.updateUser = (req, res) => {
  // 日期时间格式化
  // req.body.create_time = req.body.create_time
  //   ? formatTime(req.body.create_time)
  //   : getNowTime()
  // 查询
  const selectSql = `select * from sys_user where id <> ? and (username = ? or nick_name = ?)`
  db.query(
    selectSql,
    [req.body.id, req.body.code, req.body.name],
    (err, results) => {
      if (err) return res.new_send(err)
      // 判断用户名和昵称是否存在
      if (results.length >= 2) return res.new_send('用户名和昵称已被占用')
      if (results.length === 1) {
        const { username, nick_name } = results[0]
        const { username: name, nick_name: nc_name } = req.body
        if (username === name && nick_name === nc_name) {
          return res.new_send('用户名和昵称已被占用')
        }
        if (username === name) {
          return res.new_send('用户名已被占用')
        }
        if (nick_name === nc_name) {
          return res.new_send('昵称已被占用')
        }
      }

      //  修改数据库
      const updateSql = `update sys_user set ? where Id = ?`
      db.query(updateSql, [req.body, req.body.id], (err, results) => {
        if (err) return res.new_send(err)
        if (results.affectedRows !== 1) return res.new_send('更新用户失败')
        //todo: 处理操作日志表
        res.new_send('更新用户成功', 0)
      })
    }
  )
}

/**
 * 恢复用户
 * @param {*} req
 * @param {*} res
 */
exports.restoreUserById = (req, res) => {
  const { id } = req.params
  const deleteSql = `update sys_user set is_delete = 0 where id = ?`
  db.query(deleteSql, id, (err, results) => {
    if (err) return res.new_send(err)
    if (results.affectedRows !== 1) return res.new_send('恢复用户失败')
    res.new_send('恢复用户成功', 0)
  })
}